import React, { useState, useEffect, useRef, useImperativeHandle } from 'react';
import { Row, Col, Button } from 'antd';
import Item from './item';
import { randomKey } from 'src/utils/utils';
/**
 * @component conditions 枚举组件
 * @prop {Array} value 枚举值
 *
 */

function Conditions(props) {
  const [values, setValues] = useState([]);
  const valueRef = useRef(values)
  valueRef.current = values

  useImperativeHandle(props.createRef, () => ({
    // 暴露方法给父组件,收集值，验证应该放到这里，后面再做
    getValue: (cb) => {
      const data = valueRef.current.map(item => {
        const operatorItem = props.operator.find(item2 => item2.operator_id === item.sign)
        return {
          left: item.left,
          sign: operatorItem,
          right: item.right
        }
      })
      return data
    },
  }));

  useEffect(() => {
    initValue(props.sync_conditions)
  }, [props.sync_conditions])

  //初始化
  function initValue(values) {
    const newValue = values.map((item) => {
      return {
        id: randomKey(),
        left: item.left,
        sign: item.sign.operator_id,
        right: item.right
      }
    });
    setValues(newValue)
  }

  //添加
  function addItem() {
    const item = {
      id: randomKey(),
      left: '',
      sign: '',
      right: ''
    };
    const newValue = [...values, item]
    setValues(newValue)
  }

  // 修改item
  function handleChange(index, type, value) {
    values[index][type] = value
    const newValue = [...values]
    setValues(newValue)
  }

  // 删除
  function del(index) {
    values.splice(index, 1);
    const newValue = [...values]
    setValues(newValue)
  }

  // 移动
  function move(index, step) {
    const item = values[index]
    // 下移
    if (step === 'down') {
      values.splice(index, 1); //移除当前项
      values.splice(index + 1, 0, item); // 在index+1处插入当前item
      // 上移
    } else if (step === 'up') {
      values.splice(index, 1); //移除当前项
      values.splice(index - 1, 0, item); // 在index-1处插入当前item
    }
    const newValue = [...values]
    setValues(newValue)
  }

  return (
    <>
      <Col span={4}>
        <Button type='primary' onClick={addItem.bind(this)} style={{ marginLeft: 20 }}>+添加条件</Button>
      </Col>
      {values.length > 0 && <Col span={24}>
        <Row type='flex' justify='space-between' align='middle' gutter={10} style={{ marginBottom: 20 }}>
          <Col span={2}>序号</Col>
          <Col span={6}>左变量</Col>
          <Col span={6}>操作符</Col>
          <Col span={6}>右变量</Col>
          <Col span={4}>操作</Col>
        </Row>
        {values.map((item, index) => {
          return (
            <Item
              value={item}
              index={index}
              length={values.length}
              key={item.id}
              form={props.form}
              onChange={handleChange}
              move={move}
              del={del}
              operator={props.operator}
            />
          );
        })}
      </Col>}
    </>
  );
}

export default Conditions;